import Vue from 'vue';
import axios from "axios";
import router from '../router/index.js'
import store from "../store/store";


axios.defaults.baseURL = "http://127.0.0.1:9500/manage";

axios.defaults.headers.common['Authorization'] = store.state.token;
axios.defaults.timeout = 30000;

// 添加请求拦截器
axios.interceptors.request.use(config => {

//判断是否存在token，如果存在将每个页面header都添加token
    if (store.state.token) {
        config.headers.common['Authorization'] = store.state.token
    }
    return config;
}, error => {
// 对请求错误做些什么
    return Promise.reject(error);
});

// http response 拦截器
axios.interceptors.response.use(
    response => {

        debugger;
        if (response.data) {
            switch (response.data.code) {
                case 4001:
                case 4009:
                    store.commit('del_token');
                    router.replace({
                        path: '/',
                        query: {redirect: router.currentRoute.fullPath}
                    });
                    break;
            }
        }
        return response;
    },
    error => {
        return Promise.reject(error.response.data.message)
    });


Vue.prototype.axios = axios;
